﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Input;

using DanielVaughan.ComponentModel;
using DanielVaughan.Windows;

namespace CalciumTemplateApp.Views.Examples
{
	public class ValidationExampleViewModel : UserViewModel
	{
		public ValidationExampleViewModel() : base("validation example")
		{
			submitCommand = new DelegateCommand(
				delegate
				{
					IsComplete(
						() => MessageService.ShowMessage("Data Submitted."),
						() => MessageService.ShowMessage("Please complete the form."),
						obj => MessageService.ShowError("An error occured: " + obj.Message));
				});
		}

		readonly DelegateCommand submitCommand;

		public ICommand SubmitCommand
		{
			get
			{
				return submitCommand;
			}
		}

		string validatedString1;

		[Validate]
		public string ValidatedString1
		{
			get
			{
				return validatedString1;
			}
			set
			{
				Assign(() => ValidatedString1, ref validatedString1, value);
			}
		}

		string validatedString2;

		[Validate]
		public string ValidatedString2
		{
			get
			{
				return validatedString2;
			}
			set
			{
				Assign(() => ValidatedString2, ref validatedString2, value);
			}
		}

		protected override IEnumerable<DataValidationError> GetPropertyErrors(
			string propertyName, object value)
		{
			if (!string.IsNullOrWhiteSpace((string)value))
			{
				yield break;
			}

			switch (propertyName)
			{
				case "ValidatedString1":
					yield return new DataValidationError(1,
						"ValidatedString1 is required.");
					break;
				case "ValidatedString2":
					yield return new DataValidationError(2,
						"ValidatedString2 is required.");
					break;
			}
			yield break;
		}

		#region Asynchronous Validation
		/* Uncomment for asychronous validation. */
		//		public override void BeginValidation(string memberName, object value)
		//		{
		//			try
		//			{
		//				/* Perform validation asynchronously. */
		//				ThreadPool.QueueUserWorkItem(state => Validate(memberName, value));
		//			}
		//			catch (Exception ex)
		//			{
		//				OnValidationComplete(
		//					new ValidationCompleteEventArgs(memberName, ex));
		//			}
		//		}

		//		void Validate(string propertyName, object value)
		//		{
		//			try
		//			{
		//				IEnumerable<DataValidationError> errors
		//					= GetPropertyErrors(propertyName, value);
		//				if (errors != null && errors.Count() > 0)
		//				{
		//					OnValidationComplete(
		//						new ValidationCompleteEventArgs(propertyName, errors));
		//				}
		//				else
		//				{
		//					OnValidationComplete(
		//						new ValidationCompleteEventArgs(propertyName));
		//				}
		//			}
		//			catch (Exception ex)
		//			{
		//				OnValidationComplete(
		//					new ValidationCompleteEventArgs(propertyName, ex));
		//			}
		//		}
		#endregion
	}
}
